package edu.hawaii.ics.pjdb.worker.command_runners;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.hawaii.ics.pjdb.result_transport.TupleServiceHelper;
import edu.hawaii.ics.pjdb.types.DbSourceCommand;
import edu.hawaii.ics.pjdb.types.WorkerCommand;

/**
 * Directly runs SQL on the local db and sends all of the resulting rows to the
 * specified output location.
 * 
 * @author chris
 * 
 */
public class DbSourceRunner extends CommandRunner {
    private static final Logger logger = LoggerFactory
            .getLogger(DbSourceRunner.class);

    public DbSourceRunner(Connection localDb) {
        super(localDb);
    }

    @Override
    public void execute(WorkerCommand cmd) throws SQLException, TException {
        DbSourceCommand dbCmd = cmd.getCommand().getDbSourceCmd();
        logger.info("Running SQL query - {}, sending output to {}",
                dbCmd.getSql(), cmd.getOutputAddress());
        CallableStatement statement = localDb.prepareCall(dbCmd.getSql());
        TupleServiceHelper.submitTuples(cmd.getOutputAddress(),
                statement.executeQuery());
    }
}